import { defineStore } from 'pinia'

interface UserState {
  token: string
  userInfo: {
    id: string
    username: string
    avatar?: string
  } | null
}

export const useUserStore = defineStore('user', {
  state: (): UserState => ({
    token: '',
    userInfo: null,
  }),
  getters: {
    isLoggedIn: (state) => !!state.token,
  },
  actions: {
    setToken(token: string) {
      this.token = token
    },
    setUserInfo(userInfo: UserState['userInfo']) {
      this.userInfo = userInfo
    },
    logout() {
      this.token = ''
      this.userInfo = null
    },
  },
  persist: {
    key: 'user',
    paths: ['token'],
  },
})